package com.employmentapp;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.employmentapp.entity.ResponseInfo;
import com.employmentapp.entity.UserInfo;

/**
 * 首页
 */
public class HomeFragment extends Fragment {

    private Handler mHandler = new Handler(Looper.getMainLooper());
    private EditText mInputUsername;
    private EditText mInputPassword;
    private Button mActionLogin;
    private TextView mResult;

    public HomeFragment() {
        super(R.layout.fragment_home);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mInputUsername = view.findViewById(R.id.input_username);
        mInputPassword = view.findViewById(R.id.input_password);
        mActionLogin = view.findViewById(R.id.action_login);
        mResult = view.findViewById(R.id.result);

        mActionLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login();
            }
        });
    }

    private void login() {
        // 清空上一次的登录结果
        mResult.setText(null);

        final String username = mInputUsername.getText().toString().trim();
        final String password = mInputPassword.getText().toString().trim();
        ApiManager.getInstance().getThreadPools().execute(new Runnable() {
            @Override
            public void run() {
                // 切换到子线程请求网络
                final ResponseInfo<UserInfo> responseInfo = ApiManager.getInstance().login(username, password);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        // 切换到主线程更新 UI
                        mResult.setText("登录结果：" + responseInfo);
                    }
                });
            }
        });
    }

}
